<?php

/**
 * Domain form.
 *
 * @package    wiki
 * @subpackage form
 * @author     Elmaho
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class DomainForm extends BaseDomainForm
{
  public function configure()
  {
  	$choices = DomainTable::getListArbo();
  	
  	$this->validatorSchema['name_dom'] = new sfValidatorString(array('max_length' => 100, 'required' => true));
  	
	$entitePere = new sfWidgetFormSelect(array('choices' => $choices));
	$this->widgetSchema['parent'] = $entitePere;
	$this->validatorSchema['parent'] = new sfValidatorInteger(array('required' => false));
	
  	if($this->getObject()->getNode()->getParent()){
		$idp = $this->getObject()->getNode()->getParent()->getId();
		$this->setDefault('parent', "$idp");
		
		$this->widgetSchema['parent']->setDefault("$idp");
	}
  }
  
  public function setParent($idp){
  	$this->widgetSchema['parent']->setDefault("$idp");
  }
  
  public function doSave($con = null)
  {
  	$this->updateObject();
  	
    $parent = $this->getValue('parent');
  	if($parent && $parent > 0){
  		$parObject = Doctrine_Core::getTable('Domain')->find($parent);
        $this->getObject()->getNode()->insertAsLastChildOf($parObject);
  	}
  	else{
  		
  		$q = Doctrine_Query::create()
				    ->select('MAX(d.root_id) AS max')
				    ->from('Domain d');
  		$result = $q->fetchArray();
  		
  		$this->getObject()->setRootId($result[0]['max'] + 1);
  		$tree = Doctrine_Core::getTable('Domain')->getTree();
  		$tree->createRoot($this->getObject());
  	}
  	
  	$this->getObject()->save($con);
  }
}
